package com.bezdelnick.forum.mail.type;

import com.bezdelnick.forum.domain.Answer;
import com.bezdelnick.forum.domain.Question;
import com.bezdelnick.forum.service.ForumService;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 20.07.12
 * Time: 11:55
 * To change this template use File | Settings | File Templates.
 */
public class NotificationAnswerMail extends AbstractMail {
    private static final Logger LOGGER = LoggerFactory.getLogger(NotificationQuestionMail.class);

    private static final String NAME_LETTER = "notification_answer";

    @SpringBean
    @SuppressWarnings("unused")
    public ForumService forumService;

    public NotificationAnswerMail() {
        /* Add this instance to Spring context */
        SpringComponentInjector.get().inject(this);
    }

    @Override
    public String getTemplateName() {
        return NAME_LETTER;
    }

    @Override
    public boolean buildContext(Object object) {
        Answer answer = null;
        Question question = null;

        try {
            answer = (Answer) object;
            question = forumService.getQuestionDao().getQuestionById(answer.getQuestionId());

            this.context = new HashMap<String, Object>();
            try {
                this.context.put(
                        "username",
                        question.getUserId() == 0 ?
                                "_____" :
                                forumService.getAppUserDao().getUserById(question.getUserId()).getUsername()
                );
                this.context.put("id", answer.getQuestionId() == 0 ? 0 : answer.getQuestionId());
                this.context.put(
                        "answered_by",
                        forumService.getAppUserDao().getUserById( answer.getUserId()) == null ?
                                "____" :
                                forumService.getAppUserDao().getUserById(
                                        answer.getUserId()
                                ).getUsername()
                );
                this.context.put("date", answer.getDatePublication() == null ? "____" : answer.getDatePublication());
                return true;
            } catch (Exception e) {
                LOGGER.error(e.toString());
                LOGGER.error("It can not get mail context");
                return false;
            }
        } catch (Exception e) {
            LOGGER.warn(e.getMessage());
            return false;
        }
    }
}
